package com.linkoog.devtools.code_generator.template.loader.file;

import com.intellij.openapi.diagnostic.Logger;
import com.linkoog.devtools.PluginConstants;
import com.linkoog.devtools.code_generator.template.loader.TemplateLoader;
import com.linkoog.devtools.code_generator.template.model.node.TemplateNodeData;
import com.linkoog.devtools.code_generator.template.render.engine.TemplateType;
import com.linkoog.devtools.utils.IOUtils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 *  加载Classpath中的文件夹模板
 */
public class ClasspathDirTemplateLoader implements DirTemplateLoader{

    private static final Logger LOGGER = Logger.getInstance(ClasspathDirTemplateLoader.class);

    public TemplateNodeData loadTemplate(TemplateType templateEngineType, String templateName, String resourcePath){
        Path pluginJarPath = PluginConstants.getPluginJarPath();
        if (pluginJarPath == null) return null;

        if (resourcePath == null || resourcePath.isEmpty()) return null;
        if (resourcePath.startsWith("/")) resourcePath = resourcePath.substring(1);

        if (! resourcePath.endsWith("/")) {
            resourcePath = resourcePath + "/";
        }
        String finalResourcePath = resourcePath;
        try (InputStream inputStream = new FileInputStream(pluginJarPath.toFile())) {
            return TemplateLoader.zipToTemplate(templateEngineType, templateName, inputStream, zipEntry -> zipEntry.getName().startsWith(finalResourcePath), finalResourcePath, null);
        }catch (IOException ignored) {
        }

        return null;
    }

    private String getName(String name){
        if (name.endsWith("/")){
            name = name.substring(0,  name.length() -1);
        }

        int index = name.lastIndexOf("/");
        if (index == -1){
            return name;
        } else {
            return name.substring(index + 1);
        }
    }



}
